<template>
  <div class="flex items-center justify-center min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100">
    <!-- 登录卡片容器 -->
    <div class="w-full max-w-md p-8 space-y-8 bg-white rounded-xl shadow-2xl transform transition-all duration-300 hover:shadow-2xl">
      <!-- Logo和标题区域 -->
      <div class="text-center">
        <div class="flex justify-center mb-4">
          <img 
            src="/images/logo.png" 
            alt="PyScreenBrain Logo" 
            class="h-20 w-20 object-contain"
          />
        </div>
        <h2 class="text-2xl font-bold text-gray-900 mb-2">登录您的账户</h2>
        <p class="text-sm text-gray-600">欢迎回来，请登录您的账户</p>
      </div>

      <!-- 错误提示 -->
      <div v-if="error" class="p-3 bg-red-50 border border-red-200 rounded-lg">
        <div class="flex items-center">
          <svg class="w-5 h-5 text-red-500 mr-2" fill="currentColor" viewBox="0 0 20 20">
            <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd" />
          </svg>
          <span class="text-sm text-red-700">{{ error }}</span>
        </div>
      </div>

      <!-- 登录表单 -->
      <form @submit.prevent="handleLogin" class="space-y-6">
        <!-- 用户名/邮箱输入框 -->
        <div>
          <label for="username" class="block text-sm font-medium text-gray-700 mb-2">用户名或邮箱</label>
          <div class="relative">
            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <svg class="h-5 w-5 text-gray-400" fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clip-rule="evenodd" />
              </svg>
            </div>
            <input
              id="username"
              v-model="form.username"
              type="text"
              required
              class="block w-full pl-10 pr-3 py-3 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200"
              placeholder="请输入用户名或邮箱"
              @input="validateUsername"
            />
            <div v-if="usernameError" class="absolute inset-y-0 right-0 pr-3 flex items-center">
              <svg class="h-5 w-5 text-red-500" fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
              </svg>
            </div>
          </div>
          <p v-if="usernameError" class="mt-1 text-sm text-red-600">{{ usernameError }}</p>
        </div>

        <!-- 密码输入框 -->
        <div>
          <label for="password" class="block text-sm font-medium text-gray-700 mb-2">密码</label>
          <div class="relative">
            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <svg class="h-5 w-5 text-gray-400" fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" d="M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z" clip-rule="evenodd" />
              </svg>
            </div>
            <input
              id="password"
              v-model="form.password"
              :type="showPassword ? 'text' : 'password'"
              required
              class="block w-full pl-10 pr-10 py-3 border border-gray-300 rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200"
              placeholder="请输入密码"
            />
            <button
              type="button"
              class="absolute inset-y-0 right-0 pr-3 flex items-center"
              @click="showPassword = !showPassword"
            >
              <svg class="h-5 w-5 text-gray-400 hover:text-gray-600" fill="currentColor" viewBox="0 0 20 20">
                <path v-if="showPassword" d="M10 12a2 2 0 100-4 2 2 0 000 4z" />
                <path fill-rule="evenodd" d="M.458 10C1.732 5.943 5.522 3 10 3s8.268 2.943 9.542 7c-1.274 4.057-5.064 7-9.542 7S1.732 14.057.458 10zM14 10a4 4 0 11-8 0 4 4 0 018 0z" clip-rule="evenodd" v-else />
              </svg>
            </button>
          </div>
        </div>

        <!-- 记住我和忘记密码 -->
        <div class="flex items-center justify-between">
          <div class="flex items-center">
            <input
              id="remember-me"
              v-model="form.rememberMe"
              type="checkbox"
              class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
            />
            <label for="remember-me" class="ml-2 block text-sm text-gray-900">记住我</label>
          </div>
          <div class="text-sm">
            <router-link to="/auth/forgot-password" class="font-medium text-blue-600 hover:text-blue-500 transition-colors duration-200">忘记密码？</router-link>
          </div>
        </div>

        <!-- 登录按钮 -->
        <div>
          <button
            type="submit"
            :disabled="isLoading || hasErrors"
            class="group relative w-full flex justify-center py-3 px-4 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 transform hover:scale-[1.02] active:scale-[0.98]"
          >
            <!-- 加载动画 -->
            <svg v-if="isLoading" class="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
              <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
              <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            {{ isLoading ? '登录中...' : '立即登录' }}
          </button>
        </div>

        <!-- 注册引导 -->
        <div class="text-center">
          <p class="text-sm text-gray-600">
            还没有账户？
            <router-link to="/auth/register" class="font-medium text-blue-600 hover:text-blue-500 transition-colors duration-200">立即注册</router-link>
          </p>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '@/store/modules/auth'

// 路由和状态管理
const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()

/**
 * 登录表单数据
 */
const form = reactive({
  username: '',
  password: '',
  rememberMe: false
})

/**
 * 响应式数据
 */
const isLoading = ref(false)
const error = ref('')
const showPassword = ref(false)
const usernameError = ref('')

/**
 * 计算属性：检查是否有验证错误
 */
const hasErrors = computed(() => {
  return !!usernameError.value
})

/**
 * 验证用户名/邮箱格式
 */
const validateUsername = () => {
  const value = form.username.trim()
  
  if (!value) {
    usernameError.value = '请输入用户名或邮箱'
    return
  }
  
  // 邮箱格式验证
  if (value.includes('@')) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (!emailRegex.test(value)) {
      usernameError.value = '邮箱格式不正确'
      return
    }
  }
  
  // 用户名格式验证（至少3个字符）
  if (!value.includes('@') && value.length < 3) {
    usernameError.value = '用户名至少需要3个字符'
    return
  }
  
  usernameError.value = ''
}

/**
   * 处理登录操作
   */
  const handleLogin = async () => {
    // 验证表单
    validateUsername()
    
    if (!form.username.trim()) {
      error.value = '请输入用户名或邮箱'
      return
    }
    
    if (!form.password) {
      error.value = '请输入密码'
      return
    }
    
    if (hasErrors.value) {
      error.value = '请修正表单错误'
      return
    }

    isLoading.value = true
    error.value = ''

    try {
      await authStore.login({
        username: form.username,
        password: form.password,
        rememberMe: form.rememberMe
      })
      
      // 跳转到欢迎页面
      const redirect = route.query.redirect as string || '/welcome'
      router.push(redirect)
    } catch (err: any) {
      // 显示详细的错误信息
      error.value = err.message || '用户名或密码错误，请重试'
      console.error('登录失败:', err)
    } finally {
      isLoading.value = false
    }
  }

/**
 * 组件挂载时检查记住我状态
 */
const checkRememberMe = () => {
  const remembered = localStorage.getItem('rememberMe')
  if (remembered === 'true') {
    form.rememberMe = true
  }
}

// 调用检查函数
checkRememberMe()
</script>
